#include "tests.h"
#include <stdlib.h>
#include <assert.h>

uthread_mutex_t print_mutex;
static void print_to_screen(char* str)
{
	int count = 0,writed = 0;
	int len = strlen(str);
	while (count != len) {
		writed = uthread_write(1,str+count,sizeof(char)*(len-count));
		if (writed	>=	0)
			count += writed;
	}
	return;
}

static char* itoa(int num)
{
	if	(num == 0) 
		return "0";
	int num_digits=0,i=1;
	while (i <= num) {
		num_digits++;
		i *= 10;
	}
	char* str = (char*)malloc((num_digits+1)*sizeof(char));
	char tmp;
	str[num_digits] = '\0';
	for (i = (num_digits-1); i >= 0; i--){
		tmp = (char)(num % 10) + '0';
		num /= 10;
		str[i] = tmp;
	}
	return str;
}

static void block(uthread_mutex_t mutex) 
{
	if (uthread_mutex_lock(mutex) != MUTEX_SUCCESS) {
		print_to_screen("Unable to lock mutex.\n");
		exit(-1);
	}
}

static void unblock(uthread_mutex_t mutex) 
{
	if (uthread_mutex_unlock(mutex) != MUTEX_SUCCESS) {
		print_to_screen("Unable to unlock mutex.\n");
		exit(-1);
	}
}

static inline void delay(int n, char c) {
	int i;
	for (i = 0 ; i < n ; i++)
		i=i;
}

static inline void reset_counter()
{
	counter = 0;
}

static void msg_with_expected_order(int i, char * in, int id){
		block(print_mutex);
		print_to_screen(itoa(i));
	  print_to_screen(": ");
		print_to_screen("Thread Id= ");
		print_to_screen(itoa(id));
		print_to_screen("   ");
		print_to_screen(in);
		print_to_screen("\n");
		unblock(print_mutex);
}

static void msg(char * in){
	msg_with_expected_order(1,in,uthread_self());
}

static int fff(void* y) {
int i,j;
if(uthread_self()!=2){
	for(i=0;i<1000000;i++){
		for(j=0;j<1000;j++);
	}
}
msg("my id is \n");
return uthread_self();
}

int test12(int argc,char* argv[]){
	msg("\n************Running test #12...******************\n");
int x;

uthread_create(fff,NULL);
uthread_create(fff,NULL);
uthread_create(fff,NULL);

uthread_join(1,&x);
msg_with_expected_order(1,"lazem 1 = \n",x);
uthread_join(2,&x);
msg_with_expected_order(2,"lazem 2 = \n",x);
uthread_join(3,&x);
msg_with_expected_order(3,"lazem 3 = \n",x);
msg_with_expected_order(4,"my id is \n",uthread_self());
return 0;
}

